/**
 * 
 */
package valfazz.android.karfinder.activity;

import valfazz.android.karfinder.R;
import valfazz.android.karfinder.util.SongListView;
import android.app.Activity;
import android.database.DatabaseUtils;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * @author Val
 *
 */
public class SearchActivity extends Activity {
	private static final String TAG = "SearchActivity";
	private EditText etSearchBox;
	private Button btnClear;
	private SongListView listView;
	
	private String prefixSymbols;
	private String[] prefixKeywords;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_search);
		
		prefixSymbols = getResources().getString(R.string.search_prefix_symbols);
		prefixKeywords = getResources().getStringArray(R.array.search_prefix_keywords);
		
		listView = new SongListView(this, R.id.lvSearchList);
		
		etSearchBox = (EditText)findViewById(R.id.etSearchBox);
		etSearchBox.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				if (s.length() > 1) {
					//Log.i("length of s", s.length() + "");
					String where = null;
					String key = DatabaseUtils.sqlEscapeString(s.toString().substring(1));
					key = key.substring(1, key.length()-1);
					
					for (int i = 0; i < prefixSymbols.length(); ++i) {
						if (prefixSymbols.charAt(i) == s.charAt(0)) {
							where = prefixKeywords[i] + key + "%'";
							break;
						}
					}
										
					if (where != null)
						listView.setQuery("select SONG_ID, SONG_TITLE, SONG_LYRICS " +
								"from SONG where " + where);
				} else if (s.length() == 0){
					listView.resetList();
				}
			}

			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}});
		
		btnClear = (Button)findViewById(R.id.btnClear);
		btnClear.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				etSearchBox.setText("");
				etSearchBox.requestFocus();
			}
		});
	}

	@Override
	protected void onPause() {
		Log.i(TAG, "onPause");
		super.onPause();
		listView.closeDb();
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
		listView.openDb();
	}
}
